//
//  PostSportMomentView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/5.
//

import SwiftUI
import URLImage
import PhotosUI
import AliyunOSSiOS
import Combine
import ToastUI
import MapKit

struct PostSportMomentView: View {
    @StateObject var proModel = profileViewModel()
    @StateObject private var authManager = LocationManager()
    @EnvironmentObject var appState: AppState
    @State private var showToast = false
    @State private var isShare = false
    @FocusState private var isFocused: Bool
    @State private var content:String = ""
    @State private var images: [UIImage] = [UIImage(named: "paizhao")!]// 图片数组
    @State private var imagesUrl: [String] = []// 图片URL数组
    @State private var showActionSheet = false
    @State private var showImagePicker = false
    @State private var showPermissionAlert = false
    @State private var showLoctionAlert = false
    @State private var permissionAlertType: PermissionAlertType = .camera
    @State private var uploadUrl :String = ""
    @State private var selectedImage: UIImage?
    @State private var sourceType: UIImagePickerController.SourceType = .photoLibrary
    @StateObject private var locationService = LocationService()
    @State private var address: String?
    var body: some View {
        ZStack {
            VStack() {
                HStack {
                    Text("分享内容")
                        .font(.system(size: 16))
                        .foregroundStyle(.white)
                    Text("*")
                        .font(.system(size: 16))
                        .foregroundStyle(Color(hex: "#EF5F5F"))
                    Spacer()
                }.padding(12)
                Spacer().frame(height: 12)
                VStack {
                    ZStack(alignment: .topLeading) {
                        TextEditor(text: $content)
                            .scrollContentBackground(.hidden)
                            .frame(height: 103)
                            .foregroundColor(.white)
                            .background(.clear)
                            .padding(12)
                            .focused($isFocused)
                        if isFocused == false,content=="" {
                            Text("请输入发布内容")
                                .font(.system(size: 14))
                                .foregroundStyle(Color(hex: "#B2B2B2"))
                                .padding(12)
                        }
                    }
                    Spacer().frame(height: 16)
                    ScrollView(.horizontal) {
                        HStack(spacing: 16) {
                            ForEach(Array(images.enumerated()), id: \.offset) { index, item in
                                ZStack(alignment: .topTrailing) {
                                    Image(uiImage: item)
                                        .resizable()
                                        .frame(width: 64, height: 64)
                                        .aspectRatio(contentMode: .fill)
                                        .cornerRadius(10)
                                        .onTapGesture {
                                            //点击照片
                                            if index == images.count-1{
                                                showActionSheet = true
                                            }
                                        }
                                    if index != images.count-1 {
                                        Image(uiImage: item)
                                            .resizable()
                                            .frame(width: 64, height: 64)
                                            .aspectRatio(contentMode: .fill)
                                            .cornerRadius(10)
                                            .onTapGesture {
                                                //点击照片
                                                if index == images.count-1{
                                                    showActionSheet = true
                                                }
                                            }
                                        Image("removek")
                                            .frame(width: 20, height: 20)
                                            .padding(.top,-8)
                                            .padding(.trailing,-8)
                                            .onTapGesture {
                                                //删除照片
                                                images.remove(at: index)
                                                imagesUrl.remove(at: index)
                                            }
                                    }
                                }.frame(width:80,height:80)
                            }
                            Spacer()
                        }.padding(.horizontal,16)
                    }
                    .actionSheet(isPresented: $showActionSheet) {
                        ActionSheet(
                            title: Text("选择图片来源"),
                            buttons: [
                                .default(Text("拍照")) {
                                    checkCameraPermission()
                                },
                                .default(Text("从相册选择")) {
                                    checkPhotoLibraryPermission()
                                },
                                .cancel(Text("取消")) {
                                    showActionSheet = false
                                }
                            ]
                        )
                    }
                    .sheet(isPresented: $showImagePicker) {
                        ImagePickerView(sourceType: sourceType, selectedImage: $selectedImage)
                    }
                    .alert(isPresented: $showPermissionAlert) {
                        switch permissionAlertType {
                        case .camera:
                            Alert(
                                title: Text("相机权限被拒绝"),
                                message: Text("请在设置中允许访问相机以拍摄照片"),
                                primaryButton: .default(Text("设置")) {
                                    openSettings()
                                },
                                secondaryButton: .cancel(Text("取消"))
                            )
                        case .photoLibrary:
                            Alert(
                                title: Text("相册权限被拒绝"),
                                message: Text("请在设置中允许访问相册以选择照片"),
                                primaryButton: .default(Text("设置")) {
                                    openSettings()
                                },
                                secondaryButton: .cancel(Text("取消"))
                            )
                        }
                    }
                }
                .background(Color(hex: "#1E1E1E"))
                .cornerRadius(16)
                .frame(height: 215)
                .padding(.horizontal,12)
                
                Spacer().frame(height: 18)
                
                HStack {
                    Text("分享位置")
                        .font(.system(size: 16))
                        .foregroundStyle(.white)
                    Spacer()
                    Image("share")
                        .frame(width: 20,height: 20)
                        .onTapGesture {
                            //分享
                            checkLoctionPermission()
                        }
                }
                .frame(height: 20)
                .padding(.horizontal,12)
                .alert(isPresented: $showLoctionAlert) {
                    Alert(
                        title: Text("定位权限未开启"),
                        message: Text("请在设置中允许访问位置"),
                        primaryButton: .default(Text("设置")) {
                            openSettings()
                        },
                        secondaryButton: .cancel(Text("取消"))
                    )
                }
                
                Spacer().frame(height: 14)
                
                ZStack {
                    Image("ditu")
                        .frame(height: 120)
                        .padding(.horizontal,12)
                    if isShare {
                        AMapView(coordinate: $locationService.coordinate, address: $address)
                            .frame(height: 120)
                            .padding(.horizontal,12)
                            .cornerRadius(8)
                       
                    }
                }
                Spacer()
                HStack {
                    Button {
                        if content.isEmpty,imagesUrl.count == 0 {
                            showToast = true
                            proModel.upError = "发布内容不能为空"
                            return
                        }
                        if isShare == true,let add = address,add.isEmpty {
                            showToast = true
                            proModel.upError = "请分享定位"
                            return
                        }
                        proModel.postDynamic(userId:Int(UserConfigManager.shared.userId) ?? 0, content: content, address: address ?? "", mediaUrls: imagesUrl, createTime: Int(TimestampHelper.currentMilliTimestamp()) ?? 0)
                    } label: {
                        Text("发布")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#242424"))
                    }
                }
                .toast(isPresented: $showToast) {
                    ShowMessageView(message: proModel.upError)
                }
                .onChange(of: proModel.upError) {
                    newValue in
                    if let errorMessage = newValue, !errorMessage.isEmpty {
                        showToast = true
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                            showToast = false
                            proModel.upError = nil
                        }
                    }
                }
                .frame(maxWidth: .infinity, alignment: .center)
                .frame(height: 44)
                .gradientBackground(colors: [Color(hex: "#00F3AF"),Color(hex: "#00E9DA")], type: .linear(start: .leading, end: .trailing), cornerRadius: 22.0)
                .padding(.horizontal,12)
                .padding(.bottom,20)
            }
            .background(Color(hex: "#0A0A0A"))
            .customNavigationBar(title: "发布", backButtonAction: {
                appState.navigateBack()
            }, backgroundColor: UIColor(Color(hex: "#0A0A0A")))
        }
        .onChange(of: selectedImage) {
            newValue in
            if let image = newValue {
                OSSImageUploader.shared.uploadImage(image: image, bucketName: "kosspot-watch", objectKey: "watch-images/\(TimestampHelper.timestampToStringDay())/\(TimestampHelper.currentMilliTimestamp())") { uploadRes, error in
                    if (error == nil) {
                        uploadUrl = uploadRes
                        showToast = false
                        print(uploadRes)
                        images.insert(image, at: 0)
                        imagesUrl.insert(uploadUrl, at: 0)
                    }else {
                        proModel.upError = uploadRes
                        showToast = true
                    }
                }
            }
        }
        
        .contentShape(Rectangle())
        .onTapGesture { isFocused = false }
    }
    
    private func checkCameraPermission() {
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        permissionAlertType = .camera
        switch status {
        case .authorized:
            sourceType = .camera
            showImagePicker = true
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { granted in
                DispatchQueue.main.async {
                    if granted {
                        sourceType = .camera
                        showImagePicker = true
                    } else {
                        showPermissionAlert = true
                    }
                }
            }
        default:
            showPermissionAlert = true
        }
    }
    
    private func checkPhotoLibraryPermission() {
        let status = PHPhotoLibrary.authorizationStatus()
        permissionAlertType = .photoLibrary
        switch status {
        case .authorized:
            sourceType = .photoLibrary
            showImagePicker = true
        case .notDetermined:
            PHPhotoLibrary.requestAuthorization { newStatus in
                DispatchQueue.main.async {
                    if newStatus == .authorized {
                        sourceType = .photoLibrary
                        showImagePicker = true
                    } else {
                        showPermissionAlert = true
                    }
                }
            }
        default:
            showPermissionAlert = true
        }
    }
    
    private func openSettings() {
        if let url = URL(string: UIApplication.openSettingsURLString) {
            UIApplication.shared.open(url)
        }
    }
    
    private func checkLoctionPermission() {
        switch authManager.authorizationStatus {
        case .authorizedAlways, .authorizedWhenInUse:
            //Text("已授权定位")
            showLoctionAlert = false
            isShare = true
        case .denied:
            //Text("请到设置中开启权限")
            showLoctionAlert = true
            authManager.requestPermission()
        case .notDetermined:
            showLoctionAlert = true
            authManager.requestPermission()
        default:
            //Text("状态异常")
            showLoctionAlert = true
        }
    }
    
}



//#Preview {
//    PostSportMomentView()
//}


